from django.db import models
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _

User = get_user_model()

class DataSource(models.Model):
    """数据源模型"""
    class SourceType(models.TextChoices):
        WEIBO = 'weibo', _('微博')
        TWITTER = 'twitter', _('Twitter')
        FACEBOOK = 'facebook', _('Facebook')
        CUSTOM = 'custom', _('自定义')

    name = models.CharField(_('名称'), max_length=100)
    type = models.CharField(_('类型'), max_length=20, choices=SourceType.choices)
    credentials = models.JSONField(_('认证信息'), default=dict)
    is_active = models.BooleanField(_('是否激活'), default=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='data_sources')
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)

    class Meta:
        verbose_name = _('数据源')
        verbose_name_plural = _('数据源')
        ordering = ['-created_at']

    def __str__(self):
        return self.name

class AnalysisTask(models.Model):
    """分析任务模型"""
    class TaskType(models.TextChoices):
        SENTIMENT = 'sentiment', _('情感分析')
        TOPIC = 'topic', _('话题分析')
        USER_PROFILE = 'user_profile', _('用户画像')
        CUSTOM = 'custom', _('自定义分析')

    class TaskStatus(models.TextChoices):
        PENDING = 'pending', _('等待中')
        RUNNING = 'running', _('运行中')
        COMPLETED = 'completed', _('已完成')
        FAILED = 'failed', _('失败')
        CANCELLED = 'cancelled', _('已取消')

    name = models.CharField(_('任务名称'), max_length=100)
    type = models.CharField(_('任务类型'), max_length=20, choices=TaskType.choices)
    status = models.CharField(
        _('状态'),
        max_length=20,
        choices=TaskStatus.choices,
        default=TaskStatus.PENDING
    )
    progress = models.IntegerField(_('进度'), default=0)
    parameters = models.JSONField(_('任务参数'), default=dict)
    result = models.JSONField(_('任务结果'), null=True, blank=True)
    error_message = models.TextField(_('错误信息'), blank=True)
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='analysis_tasks')
    data_source = models.ForeignKey(DataSource, on_delete=models.SET_NULL, null=True, related_name='tasks')
    
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)
    completed_at = models.DateTimeField(_('完成时间'), null=True, blank=True)

    class Meta:
        verbose_name = _('分析任务')
        verbose_name_plural = _('分析任务')
        ordering = ['-created_at']

    def __str__(self):
        return self.name

class AnalysisResult(models.Model):
    """分析结果模型"""
    class VisualizationType(models.TextChoices):
        LINE = 'line', _('折线图')
        BAR = 'bar', _('柱状图')
        PIE = 'pie', _('饼图')
        SCATTER = 'scatter', _('散点图')
        TABLE = 'table', _('表格')
        TEXT = 'text', _('文本')

    title = models.CharField(_('标题'), max_length=100)
    description = models.TextField(_('描述'), blank=True)
    data = models.JSONField(_('数据'))
    visualization_type = models.CharField(
        _('可视化类型'),
        max_length=20,
        choices=VisualizationType.choices,
        default=VisualizationType.TABLE
    )
    
    task = models.ForeignKey(AnalysisTask, on_delete=models.CASCADE, related_name='analysis_results')
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)

    class Meta:
        verbose_name = _('分析结果')
        verbose_name_plural = _('分析结果')
        ordering = ['-created_at']

    def __str__(self):
        return self.title

class Report(models.Model):
    REPORT_TYPE_CHOICES = (
        ('overview', '数据概览报表'),
        ('trend', '趋势分析报表'),
        ('user', '用户分析报表'),
        ('content', '内容分析报表'),
        ('custom', '自定义报表'),
    )
    
    STATUS_CHOICES = (
        ('processing', '生成中'),
        ('completed', '已完成'),
        ('failed', '失败'),
    )
    
    name = models.CharField(_('报表名称'), max_length=100)
    type = models.CharField(_('报表类型'), max_length=20, choices=REPORT_TYPE_CHOICES)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reports', verbose_name=_('用户'))
    data_source = models.ForeignKey('DataSource', on_delete=models.CASCADE, related_name='reports', verbose_name=_('数据源'))
    metrics = models.JSONField(_('报表指标'), default=list)
    parameters = models.JSONField(_('报表参数'), default=dict)
    result = models.JSONField(_('报表结果'), default=dict, null=True, blank=True)
    status = models.CharField(_('状态'), max_length=20, choices=STATUS_CHOICES, default='processing')
    error_message = models.TextField(_('错误信息'), null=True, blank=True)
    task_id = models.CharField(_('任务ID'), max_length=100, null=True, blank=True)
    start_date = models.DateField(_('开始日期'))
    end_date = models.DateField(_('结束日期'))
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)
    
    class Meta:
        verbose_name = _('报表')
        verbose_name_plural = _('报表')
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name
